package com.scisoft.scan.control.depotoutchange;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;

import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nlscan.android.scan.ScanManager;
import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.control.CommonAdapter;
import com.scisoft.scan.control.CommonViewHolder;
import com.scisoft.scan.data.BarCodeBean;
import com.scisoft.scan.data.PartBean;
import com.scisoft.scan.data.depotoutchange.DOCOrderBean;
import com.scisoft.scan.data.depotoutchange.DOCOrderDetailBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper;
import com.scisoft.scan.ws.WebServiceHelper_DepotOutChange;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class DOCOrderDetailActivity extends Activity {

    private ImageView iv_Back; //返回按钮
    private ImageView iv_add; //增加按钮
    private TextView tv_submit;
    private ClearEditText et_bar;
    private ImageView iv_scan;
    private List<DOCOrderDetailBean> depotOrderDetailBeanList;
    private DOCOrderBean orderBean;
    private String orderState;//0 未完成 1已完成
    private TextView tv_count;//数量

    DOCDetailAdapter docDetailAdapter;
    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLayoutManager;
    float lastY = 0;

    //返回当前界面
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        QueryDepotOrder();
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//即隐藏标题栏
        setContentView(R.layout.activity_docorder_detail);

        depotOrderDetailBeanList = new ArrayList<>();
        //参数传递
        Intent intent = getIntent();
        orderBean = (DOCOrderBean) intent.getSerializableExtra("data");
        //控件初始化
        tv_submit = findViewById(R.id.tv_submit);
        //提交按钮
        tv_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtil.showPress(DOCOrderDetailActivity.this);
                CompletePartOrderTask completePartOrderTask = new CompletePartOrderTask(DOCOrderDetailActivity.this);
                completePartOrderTask.execute();
            }
        });
        //显示区域按钮
//        TextView tv_title = findViewById(R.id.tv_title);
//        tv_title.setText(orderBean.supplierName);
        TextView tv_orderNo = findViewById(R.id.tv_orderNo);
        tv_orderNo.setText(orderBean.orderNo);
        TextView tv_depotName = findViewById(R.id.tv_depotName);
        tv_depotName.setText(orderBean.depotName);
        tv_count = findViewById(R.id.tv_count);

        String temp = orderBean.orderState;
        if(temp!=null && temp.contains("完成")){
            orderState = "1";
        }else {
            orderState = "0";
        }
        if (orderState.equals("1")) {
            tv_submit.setVisibility(View.INVISIBLE);
        } else {
            tv_submit.setVisibility(View.VISIBLE);
        }

        et_bar = findViewById(R.id.et_bar);
        iv_scan = findViewById(R.id.iv_scan);
        iv_scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String barCode = et_bar.getText().toString();
                if (!"".equals(barCode)) {
                    try {
                        ScanData(barCode);
                    } catch (Exception e) {
                        Toast.makeText(DOCOrderDetailActivity.this, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                    }

                }
            }
        });

        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //增加
        iv_add = findViewById(R.id.iv_add);
        iv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DOCOrderDetailActivity.this, DOCPartQueryActivity.class);
                intent.putExtra("data", orderBean);
                startActivityForResult(intent,0);
            }
        });

        //列表
        mRefreshLayout = findViewById(R.id.swipe_layout);
        mRefreshLayout.setProgressViewEndTarget(true, 0);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mRefreshLayout.setRefreshing(false);
                CommonUtil.showPress(DOCOrderDetailActivity.this);
                QueryDepotOrderTask queryLastOperatorTask = new QueryDepotOrderTask(DOCOrderDetailActivity.this);
                queryLastOperatorTask.execute();
            }
        });
        mRecyclerView = findViewById(R.id.lv_data);
        docDetailAdapter = new DOCDetailAdapter(DOCOrderDetailActivity.this);
        docDetailAdapter.setMultiPage(false);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int fullWidth = displayMetrics.widthPixels;
        docDetailAdapter.setItemLayout(R.layout.item_docorderdetail, R.id.hsv, R.id.layout_show, R.id.layout_hide, fullWidth);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //点击弹窗
        docDetailAdapter.setOnItemClickListener(new DOCDetailAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                DOCOrderDetailBean docOrderDetailBean = docDetailAdapter.getItemData(position);
                if (docOrderDetailBean != null) {
                    if("0".equals(docOrderDetailBean.ifGyssm)){
                        alert_edit(docOrderDetailBean);
                    }
                }
            }
        });
        //滚动的时候清空左滑按钮
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        if (Math.abs(event.getY() - lastY) > 5)
                            docDetailAdapter.clearLeftMenuList();
                }
                return false;
            }
        });
        mRecyclerView.setAdapter(docDetailAdapter);


        //查询
        CommonUtil.showPress(this);
        QueryDepotOrderTask queryLastOperatorTask = new QueryDepotOrderTask(DOCOrderDetailActivity.this);
        queryLastOperatorTask.execute();
    }

    //自定义弹出窗口
    private void alert_edit(final DOCOrderDetailBean dosOrderDetailBean) {
        //1.创建一个Dialog对象,去除标题栏
        final Dialog mDialog = new Dialog(this);
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //2.填充布局,将自定义布局设置进去
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.dialog_docorderdetail, null);
        mDialog.setContentView(dialogView);
        //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        Window window = mDialog.getWindow();
        lp.copyFrom(window.getAttributes());
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
        mDialog.show();
        window.setAttributes(lp);

        //4、设置点击其它地方不让消失弹窗
        mDialog.setCancelable(false);
        //5、初始化控件
        TextView tv_dtlNo = dialogView.findViewById(R.id.tv_dtlNo);
        tv_dtlNo.setText(dosOrderDetailBean.partNo);
        TextView tv_dtlName = dialogView.findViewById(R.id.tv_dtlName);
        tv_dtlName.setText(dosOrderDetailBean.partName);
        TextView tv_dtlInfo = dialogView.findViewById(R.id.tv_dtlInfo);
        tv_dtlInfo.setText(dosOrderDetailBean.supplierCode + " " + dosOrderDetailBean.supplierName);

        final TextView tv_amount = dialogView.findViewById(R.id.tv_amount);
        final TextView et_price = dialogView.findViewById(R.id.et_price);
        final EditText et_count = dialogView.findViewById(R.id.et_count);
        //初始化

        int count = Integer.parseInt(et_count.getText().toString());
        double price = Double.parseDouble(dosOrderDetailBean.price);
        double amount = new BigDecimal(count * price).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        et_count.setText(String.valueOf(dosOrderDetailBean.partCount));
        et_price.setText(String.valueOf(dosOrderDetailBean.price));
        tv_amount.setText(String.valueOf(amount));

        et_count.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    int count = Integer.parseInt(et_count.getText().toString());
                    double price = Double.parseDouble(dosOrderDetailBean.price);
                    double amount = new BigDecimal(count * price).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    tv_amount.setText(String.valueOf(amount));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        TextView tv_minus = dialogView.findViewById(R.id.tv_minus);
        tv_minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int count = Integer.parseInt(et_count.getText().toString());
                int temp = count - 1;
                if (temp <= 0) {
                    Toast.makeText(getApplicationContext(), "数量不能小于0", Toast.LENGTH_LONG).show();
                    return;
                } else {
                    et_count.setText(String.valueOf(temp));
                }
            }
        });

        TextView tv_add = dialogView.findViewById(R.id.tv_add);
        tv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int count = Integer.parseInt(et_count.getText().toString()) + 1;
                et_count.setText(String.valueOf(count));
            }
        });


        TextView tv_ok = dialogView.findViewById(R.id.tv_ok);
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //按下确定键后的事件
                DOCOrderDetailBean newData = dosOrderDetailBean;
                newData.partCount = et_count.getText().toString();
                CommonUtil.showPress(DOCOrderDetailActivity.this);
                ScanUpdateTask updateTask = new ScanUpdateTask(DOCOrderDetailActivity.this, newData);
                updateTask.execute();
                mDialog.dismiss();
            }
        });
        TextView tv_cancel = (TextView) dialogView.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
    }

    //绑定数据
    private void BindData(Context context) {
        //更新数据
        if (depotOrderDetailBeanList == null || depotOrderDetailBeanList.size() == 0) {
            mRecyclerView.setVisibility(View.INVISIBLE);
            tv_count.setText("(0)");

        } else {
            mRecyclerView.setVisibility(View.VISIBLE);
            //数据
            docDetailAdapter.clearLeftMenuList();
            docDetailAdapter.clearAddItem(depotOrderDetailBeanList);
            tv_count.setText("(" + String.valueOf(depotOrderDetailBeanList.size()) + ")");
        }
    }

    //查询订单明细
    private void QueryDepotOrder() {
        CommonUtil.showPress(this);
        QueryDepotOrderTask QueryPackInfoTask = new QueryDepotOrderTask(DOCOrderDetailActivity.this);
        QueryPackInfoTask.execute();
    }

    //查询订单明细服务
    class QueryDepotOrderTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryDepotOrderTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                depotOrderDetailBeanList = WebServiceHelper_DepotOutChange.DEPOT_OUT_CHANGE_03(orderBean.orderId);
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //更新扫码明细服务
    class ScanUpdateTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private DOCOrderDetailBean docOrderDetailBean;

        ScanUpdateTask(Context context, DOCOrderDetailBean docOrderDetailBean) {
            super();
            mcontext = context;
            this.docOrderDetailBean = docOrderDetailBean;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_DepotOutChange.DEPOT_OUT_CHANGE_05(orderBean.orderId, docOrderDetailBean);
                if (msg.contains("成功")) {
                    depotOrderDetailBeanList = WebServiceHelper_DepotOutChange.DEPOT_OUT_CHANGE_03(orderBean.orderId);
                }

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //删除扫码明细服务
    class ScanDeleteTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private DOCOrderDetailBean docOrderDetailBean;

        ScanDeleteTask(Context context, DOCOrderDetailBean docOrderDetailBean) {
            super();
            mcontext = context;
            this.docOrderDetailBean = docOrderDetailBean;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_DepotOutChange.DEPOT_OUT_CHANGE_06(orderBean.orderId, docOrderDetailBean.dtlId);
                if (msg.contains("成功")) {
                    depotOrderDetailBeanList = WebServiceHelper_DepotOutChange.DEPOT_OUT_CHANGE_03(orderBean.orderId);
                }

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //全部拣货提交服务
    class CompletePartOrderTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        CompletePartOrderTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_DepotOutChange.DEPOT_OUT_CHANGE_07(orderBean.orderId);

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                finish();
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    class DOCDetailAdapter extends CommonAdapter<DOCOrderDetailBean> {

        //构造函数
        public DOCDetailAdapter(Context context) {
            super(context);
        }

        @Override
        public void convert(CommonViewHolder holder, final DOCOrderDetailBean docOrderDetailBean, int position) {
            //获取相应索引的ItemBean对象
            final DOCOrderDetailBean bean = mList.get(position);
            //配件信息
            TextView tv_partInfo = holder.getView(R.id.tv_partInfo);
            //供应商信息
            TextView tv_supplierInfo = holder.getView(R.id.tv_supplierInfo);
            //有码件
            TextView tv_ymj = holder.getView(R.id.tv_ymj);
            //唯一码
            TextView tv_serialNo = holder.getView(R.id.tv_serialNo);
            //数量
            TextView tv_partCount = holder.getView(R.id.tv_partCount);
            //单价
            TextView tv_price = holder.getView(R.id.tv_price);

            //设置控件的对应属性值
            tv_partCount.setText("数量:" + String.valueOf(bean.partCount));
            String ymj = "有码件";
            if ("0".equals(bean.ifGyssm)) {
                ymj = "无码件";
                tv_serialNo.setVisibility(View.GONE);
            } else {
                tv_serialNo.setVisibility(View.VISIBLE);
                tv_serialNo.setText(bean.serialNo);
            }
            //有码件
            tv_ymj.setText(ymj);
            //配件信息
            tv_partInfo.setText(bean.partNo + " " + bean.partName);
            //供应商信息
            tv_supplierInfo.setText(bean.supplierCode + " " + bean.supplierName);
            //单价
            tv_price.setText(bean.price);


            //按钮(删除)
            TextView tv_delete = holder.getView(R.id.tv_delete);
            tv_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CommonUtil.showPress(DOCOrderDetailActivity.this);
                    ScanDeleteTask deleteTask = new ScanDeleteTask(DOCOrderDetailActivity.this, bean);
                    deleteTask.execute();
                }
            });
        }
    }

    //region 以下为扫码相关

    //查询条码服务
    class QueryBarCodeTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String barCode;
        private BarCodeBean barCodeBean = null;

        QueryBarCodeTask(Context context, String barCode) {
            super();
            mcontext = context;
            this.barCode = barCode;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                barCodeBean = WebServiceHelper.ParseBarCode(barCode);
                if (barCodeBean.barType == BarCodeBean.BAR_PART) {
                    PartBean partBean = barCodeBean.partBean;
                    if (partBean == null) {
                        msg = "无效配件条码";
                        return msg;
                    } else {
                        //生成配件
                        DOCOrderDetailBean docOrderDetailBean = new DOCOrderDetailBean();
                        docOrderDetailBean.partCount = "1";
                        docOrderDetailBean.supplierCode = partBean.supplierCode;
                        docOrderDetailBean.supplierName = partBean.supplierName;
                        docOrderDetailBean.partNo = partBean.partNo;
                        docOrderDetailBean.partName = partBean.partName;
                        docOrderDetailBean.ifGyssm = "1";
                        docOrderDetailBean.serialNo = partBean.serialNo;

                        msg = WebServiceHelper_DepotOutChange.DEPOT_OUT_CHANGE_04(orderBean.orderId, docOrderDetailBean);

                        if (msg.contains("成功")) {
                            depotOrderDetailBeanList = WebServiceHelper_DepotOutChange.DEPOT_OUT_CHANGE_03(orderBean.orderId);
                        }
                    }
                } else {
                    msg = "无效配件条码";
                    return msg;
                }
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //扫码服务
    private void ScanData(String barCode) {
        if (barCode != null && barCode.length() > 0) {
            CommonUtil.showPress(this);
            QueryBarCodeTask queryBarCodeTask = new QueryBarCodeTask(DOCOrderDetailActivity.this, barCode);
            queryBarCodeTask.execute();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    //注册广播
    private void registerReceiver() {
        IntentFilter intFilter = new IntentFilter(ScanManager.ACTION_SEND_SCAN_RESULT);
        registerReceiver(mResultReceiver, intFilter);
    }

    //取消注册广播
    private void unRegisterReceiver() {
        try {
            unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
            Toast.makeText(this, "注销扫码失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    //监听扫码数据的广播，当设置广播输出时作用该方法获取扫码数据
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ScanManager.ACTION_SEND_SCAN_RESULT.equals(action)) {
                byte[] bvalue1 = intent.getByteArrayExtra(ScanManager.EXTRA_SCAN_RESULT_ONE_BYTES);
                String svalue1 = null;
                try {
                    if (bvalue1 != null) {
                        svalue1 = new String(bvalue1, "GBK");
                        ScanData(svalue1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(DOCOrderDetailActivity.this, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };
    //endregion

}
